<template>
  <zc-card>
    <avue-crud
      ref="crud"
      :option="option"
      :page.sync="page"
      :table-loading="loading"
      @on-load="getList"
      @row-update="rowUpdate"
      :upload-after="uploadAfter"
      :upload-before="uploadBefore"
      @row-save="rowSave"
      @row-del="rowDel"
      @refresh-change="refreshChange"
      @search-reset="searchChange"
      @search-change="searchChange"
      v-model="form"
      :data="data"
      :permission="permission"
    >
      <template slot="avatar" slot-scope="scope">
        <img
          class="column-img-avatar"
          :src="scope.row.avatar"
          @click="$ImagePreview([{ url: scope.row.avatar }], 0)"
        />
      </template>
      <template slot="state" slot-scope="scope">
        <el-switch
          :disabled="!permission.editBtn"
          @change="
            (e) => {
              switchChange(e, scope.row.id);
            }
          "
          v-model="scope.row.state"
          :active-value="1"
          :inactive-value="2"
          active-color="#1890ff"
          inactive-color="#DCDFE6"
        ></el-switch>
      </template>
      <template slot="is_adv" slot-scope="scope">
        <el-tag v-if="scope.row.is_adv == 1">{{ scope.row.$is_adv }}</el-tag>
        <el-tag type="danger" v-if="scope.row.is_adv == 2">{{
          scope.row.$is_adv
        }}</el-tag>
      </template>
      <template slot="is_edition" slot-scope="scope">
        <el-tag v-if="scope.row.is_edition == 1">{{
          scope.row.$is_edition
        }}</el-tag>
        <el-tag type="danger" v-if="scope.row.is_edition == 2">{{
          scope.row.$is_edition
        }}</el-tag>
      </template>

      <template slot="is_pay" slot-scope="scope">
        <el-tag v-if="scope.row.is_pay == 1">{{ scope.row.$is_pay }}</el-tag>
        <el-tag type="danger" v-if="scope.row.is_pay == 2">{{
          scope.row.$is_pay
        }}</el-tag>
      </template>

      <template slot="is_open_vip" slot-scope="scope">
        <el-tag v-if="scope.row.is_open_vip == 1">{{
          scope.row.$is_open_vip
        }}</el-tag>
        <el-tag type="danger" v-if="scope.row.is_open_vip == 2">{{
          scope.row.$is_open_vip
        }}</el-tag>
      </template>

      <template slot-scope="scope" slot="menu">
        <el-button
          v-if="permission.editBtn"
          :type="scope.type"
          icon="el-icon-edit"
          :size="scope.size"
          @click.stop="handleEdit(scope.row, scope.index)"
          >编辑</el-button
        >
        <el-button
          v-if="permission.editBtn"
          :type="scope.type"
          icon="el-icon-lock"
          :size="scope.size"
          @click.stop="handlePassword(scope.row, scope.index)"
          >修改密码</el-button
        >
        <el-button
          v-if="permission.delBtn"
          :type="scope.type"
          icon="el-icon-delete"
          :size="scope.size"
          @click.stop="handleDel(scope.row, scope.index)"
          >删除</el-button
        >
      </template>
    </avue-crud>
  </zc-card>
</template>

<script>
import { mapGetters } from "vuex";
import {
  getList,
  update,
  add,
  del,
  getRoleList,
  updateStatus,
} from "@/api/admin/admin_user.js";
import option from "./admin_user-options.js";

export default {
  name: "admin_user",
  data() {
    return {
      permission: {
        addBtn: false,
        editBtn: false,
        delBtn: false,
      }, //权限
      page: {
        currentPage: 1,
        pageSize: 10,
      },
      form: {},
      params: {},
      loading: false,
      data: [],
      option: {},
    };
  },
  created() {
    const role = this.$defaultRoleStatus;
    this.permission.addBtn = this.zcbtn[this.$options.name + "_add"] || role;
    this.permission.editBtn = this.zcbtn[this.$options.name + "_edit"] || role;
    this.permission.delBtn = this.zcbtn[this.$options.name + "_del"] || role;
    this.option = option(this);
  },
  mounted() {},
  computed: {
    ...mapGetters(["zcbtn"]),
  },
  methods: {
    // 切换状态
    switchChange(e, id) {
      if (e == 1) {
        updateStatus({ field: "state", value: 1, id }).then((res) => {
          this.$notify({
            title: "成功",
            message: "修改状态成功",
            type: "success",
          });
        });
      }
      if (e == 2) {
        updateStatus({ field: "state", value: 2, id }).then((res) => {
          this.$notify({
            title: "成功",
            message: "修改状态成功",
            type: "success",
          });
        });
      }
    },
    // 修改密码
    handlePassword(row, index) {
      this.$prompt("请输入密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputValidator: (e) => {
          if (!e) {
            return "密码不能为空";
          }
          if (e.trim().length < 3) {
            return "密码长度不能小于3位";
          }

          return true;
        },
      }).then(({ value }) => {
        updateStatus({
          id: row.id,
          value,
          field: "password",
        }).then((res) => {});
        this.$message({
          type: "success",
          message: "修改密码成功",
        });
      });
    },
    // 自定义删除
    handleDel(row, index) {
      this.$refs.crud.rowDel(row, index);
    },
    // 自定义编辑
    handleEdit(row, index) {
      this.$refs.crud.rowEdit(row, index);
    },
    uploadAfter(res, done) {
      // console.log(res, "上传");

      done();
    },

    // 上传前
    uploadBefore(file, done, loading) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      let index = file.name.lastIndexOf(".");
      let suffix = file.name.substr(index + 1);
      // 图片处理
      if (suffix == "png" || suffix == "jpg" || suffix == "jpeg") {
        if (!isLt2M) {
          loading();
          this.$message.error("上传图片大小不能超过 10MB!");
          return;
        } else {
          done();
          return;
        }
      } else {
        loading();
        this.$message.error("请上传正确的格式的文件");
        return;
      }

      // 文件处理

      // if (
      //   suffix == "pdf" ||
      //   suffix == "doc" ||
      //   suffix == "docx" ||
      //   suffix == "xlsx"
      // ) {
      //   this.form.info_files_name.push(fileName);
      //   this.form.info_files_suffix.push(suffix);
      //   done();
      //   return;
      // }

      // 什么都不是

      // if (suffix) {
      //   loading();
      //   this.$message.error("请上传正确的格式");
      // }
    },
    getList() {
      this.loading = true;
      const data = Object.assign(
        {
          page: this.page.currentPage,
          limit: this.page.pageSize,
        },
        this.params
      );
      this.data = [];

      return getList(data).then((res) => {
        this.loading = false;
        this.page.total = res.num;
        this.data = res.data;
        return Promise.resolve(true);
      });
    },
    rowSave(row, done, loading) {
      // return;
      add(
        Object.assign(
          {
            role_id: row.role_name,
          },
          row
        )
      )
        .then(() => {
          this.$message.success("新增成功");
          done();
          this.getList();
        })
        .catch(() => {
          loading();
        });
    },
    rowUpdate(row, index, done, loading) {
      delete row.password;
      update(
        Object.assign(
          {
            role_id: row.role_name,
          },
          row
        )
      )
        .then(() => {
          this.$message.success("修改成功");
          done();
          this.getList();
        })
        .catch(() => {
          loading();
        });
    },
    rowDel(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return del(row.id);
        })
        .then(() => {
          this.$message.success("删除成功");
          this.getList();
        });
    },
    async searchChange(params, done) {
      // console.log(params);
      if (params.add_time && params.add_time.length > 0) {
        params.start_time = params.add_time[0].getTime() / 1000;
        params.end_time = params.add_time[1].getTime() / 1000;
      }
      if (done) done();
      this.params = params;
      this.page.currentPage = 1;
      await this.getList();
      this.$message.success("搜索成功");
    },
    async refreshChange() {
      await this.getList();
      this.$message.success("刷新成功");
    },
  },
};
</script>

<style lang="scss" scoped>
.column-img-avatar {
  height: 40px;
  width: 40px;
  border-radius: 50%;
}
</style>